package cn.fl.spl.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.condition.SysOrgQueryCondition;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.user.facade.system.dto.SysUsrDatAuthRDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.spl.service.ISplPositionInfoService;
import cn.fl.spl.service.ISplVisitRecService;
import cn.fl.spl.transform.SplVisitRecDataAnalysisVOTransform;
import cn.fl.spl.transform.SplVisitRecVOTransform;
import cn.fl.spl.vo.SplPositionInfoVO;
import cn.fl.spl.vo.SplVisitRecDataAnalysisVO;
import cn.fl.spl.vo.SplVisitRecVO;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.spl.facade.framework.constant.DictionaryConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.api.ISplVisitRecApiService;
import fl.spl.facade.spl.condition.SplInfoQueryCondition;
import fl.spl.facade.spl.condition.SplPositionInfoQC;
import fl.spl.facade.spl.condition.SplRlPsnQueryCondition;
import fl.spl.facade.spl.condition.SplVisitRecQC;
import fl.spl.facade.spl.dto.SplInfoDTO;
import fl.spl.facade.spl.dto.SplRlPsnDTO;
import fl.spl.facade.spl.dto.SplVisitRecDTO;
import fl.spl.facade.spl.dto.SplVisitRecDataAnalysisDTO;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 供应商拜访记录 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get*
 *               批量：batch* 查询集合：search*
 */
@Service
public class SplVisitRecServiceImpl implements ISplVisitRecService {

	/**
	 * 供应商拜访记录API
	 */
	@Autowired
	private ISplVisitRecApiService splVisitRecApiService;

	/**
	 * 数据字典
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	/**
	 * SplPositionInfo 服务层BEAN
	 */
	@Autowired
	private ISplPositionInfoService splPositionInfoService;
	/**
	 * 组织架构服务
	 */
	@Autowired
	private ISysOrgApiService sysOrgApiService;
	/**
	 * 供应商服务
	 */
	@Autowired
	private ISplInfoApiService splInfoApiService;
	/**
	 * 地区服务
	 */
	@Autowired
	private ISysRegionApiService sysRegionApiService;
	/**
	 * 权限模块对外暴露接口
	 */
	@Autowired
	private IPriorityApiService priorityApiService ;

	@Override
	public SplVisitRecVO selectById(Long id) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "获取对象主键不能为空!");
		}
		// TODO 业务逻辑
		SplVisitRecDTO dto = null;// this.自定义ApiService.selectSplVisitRecDTOById(id);
		return SplVisitRecVOTransform.toVO(dto);
	}

	@Override
	public Long add(SplVisitRecVO entity) throws BaseException {
		if (null == entity) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "新增对象不存在!");
		}
		;
		// return
		// this.splVisitRecApiService.add(SplVisitRecVOTransform.toDTO(entity));
		// TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "删除对象主键不能为空!");
		}
		;
		// return this.splVisitRecApiService.removeSplVisitRecDTOById(id);
		// TODO 业务逻辑
		return false;
	}

	/**
	 * 删除
	 *
	 * @param ids
	 * @return
	 */
	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException {
		if (CollectionUtils.isEmpty(ids)) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "删除对象主键不能为空!");
		}
		;
		return false;
	}

	@Override
	public boolean modify(SplVisitRecVO entity) throws BaseException {
		if (null == entity) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "修改对象不能为空!");
		}
		;
		// return
		// this.splVisitRecApiService.modifySplVisitRecDTO(SplVisitRecVOTransform.toDTO(entity));
		// TODO 业务逻辑
		return false;
	}

	/**
	 * 分页查询所有
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Pager searchListPage(Pager page) throws BaseException {
		if (null == page) {
			page = new Pager();
		}
		Pager pager = this.splVisitRecApiService.searchSplVisitRecListPage(page);
		List<SplVisitRecDTO> resultList = (List<SplVisitRecDTO>) pager.getResultList();
		if (CollectionUtils.isNotEmpty(resultList)) {
			List<SplVisitRecVO> list = this.dataPackage(SplVisitRecVOTransform.toVOList(resultList));
			pager.setResultList(list);
		}
		return pager;
	}

	/**
	 * 导出拜访记录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String exportVisitRec(Pager page,String isBisic) throws BaseException {
	    if(null == page){
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "page不能为空！");
        }
		Pager searchSplVisitRecListPage = new Pager();
        if(StringUtils.isNotEmpty(isBisic) && BaseConstant.IS_YESNO_YES_STR.equals(isBisic)){
            searchSplVisitRecListPage = this.splVisitRecApiService.selectSplBisicVisitRecListPage(page);
        }else{
            searchSplVisitRecListPage = this.splVisitRecApiService.searchSplVisitRecListPage(page);
        }
		List<SplVisitRecDTO> visitList = (List<SplVisitRecDTO>) searchSplVisitRecListPage.getResultList();
		List<SplVisitRecVO> list = SplVisitRecVOTransform.toVOList(visitList);
		list = this.dataPackage(list);
		for (SplVisitRecVO splVisitRecVO : list) {
			if (1 == splVisitRecVO.getIsDel()) {
				splVisitRecVO.setIsValid(2);
			}
		}
		ExportParams params = new ExportParams(null, null, ExcelType.XSSF);
		params.setTitleHeight((short) 5);
		params.setColor(HSSFColor.GREY_25_PERCENT.index);// 表头颜色
		params.setHeaderColor(HSSFColor.WHITE.index);
		Workbook workbook = (Workbook) ExcelExportUtil.exportExcel(params, SplVisitRecVO.class, list);
		String filePath = "visitrec";
		String serverFilePath = this.getServerFilePath(filePath);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		serverFilePath = serverFilePath + "拜访记录" + sdf.format(new Date()) + ".xlsx";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(serverFilePath);
			workbook.write(fos);
			fos.flush();
		} catch (FileNotFoundException e) {
			BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, e.getMessage());
		} catch (Exception e) {
			BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700,
					BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
		} finally {
			try {
				if (null != fos) {
					fos.close();
				}
			} catch (IOException e) {
				BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.setThrowable(e)
						.error(LogExceptionEnum.COMMON_CODE_0099);
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700,
						BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
			}
		}
		String serverPath = serverFilePath.replace(
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		return serverPath;
	}

	/**
	 * 创建文件服务器保存路径
	 */
	private String getServerFilePath(String filePath) throws BaseException {
		String prifixPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);// 根目录
		StringBuffer savePath = new StringBuffer(prifixPath);// 最终保存路径
		if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾,不是加入斜杠
			savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
		}
		savePath.append(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.UPLOAD_COSTOMER_PATH));// 自定义代码-其中包括系统代码
		if (StringUtils.isNotEmpty(filePath)) {// 如果不等于空则加入
			if (filePath.startsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"开头
				savePath.append(filePath.substring(1));
			} else {
				savePath.append(filePath);
			}

		}
		if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾
			savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
		}
		String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
		savePath.append(currentTime);
		savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
		// 检查目录
		File pathFile = new File(savePath.toString());
		// File pathFile = new File("C:/home/");
		if (!pathFile.exists()) {
			// 文件夹不存 创建文件
			boolean createPath = pathFile.mkdirs();
			if (!createPath) {
				throw new BaseException(BaseExceptionConstant.COMMON_0001, "服务器附件目录未创建成功!");
			}
		}
		return savePath.toString();
		// return "C:/home/";
	}

	private List<SplVisitRecVO> dataPackage(List<SplVisitRecVO> list) throws BaseException {
		List<Long> splIds = new ArrayList<Long>();
		for (SplVisitRecVO vo : list) {
			splIds.add(vo.getSplId());
		}

		// 拜访目的数据字典查询
		Map<String, String> purpCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.SPL_SYS_CD,
				SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.VISIT_PURP_CD);
		// 联系人类型数据字典查询
		Map<String, String> conTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.SPL_SYS_CD,
				SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CON_TYP_CD);
		// 查询供应商地理位置信息
		SplPositionInfoQC splPositionInfoQC = new SplPositionInfoQC();
		splPositionInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
		splPositionInfoQC.setIsValid(BaseConstant.IS_YESNO_YES);
		splPositionInfoQC.setSplIdList(splIds);
		List<SplPositionInfoVO> positionList = this.splPositionInfoService.searchList(splPositionInfoQC);
		// 查询部门信息
		List<SysOrgDTO> sysOrgList = this.sysOrgApiService.searchSysOrgList(new SysOrgQueryCondition());
		//查询供应商信息
		SplInfoQueryCondition splInfoCondition = new SplInfoQueryCondition();
		splInfoCondition.setIds(splIds);
		splInfoCondition.setIsDel(9);
		List<SplInfoDTO> splInfoList = this.splInfoApiService.searchSplInfoList(splInfoCondition);
		// 查询联系人集合
		SplRlPsnQueryCondition rlPsnCondition = new SplRlPsnQueryCondition();
		rlPsnCondition.setSplIdList(splIds);
		List<SplRlPsnDTO> rlPsnList = this.splInfoApiService.searchPrdSplRlPsnList(rlPsnCondition, SplSystemConstant.SPL_SYS_CD, 
				CurrentThreadContext.getCurrentOrgCd());
		
		List<String> rgnCdList = new ArrayList<String>();
		for (SplInfoDTO splInfoDTO : splInfoList) {
			if (StringUtils.isNotEmpty(splInfoDTO.getRgnPrCd())) {
				rgnCdList.add(splInfoDTO.getRgnPrCd());
			}
			if (StringUtils.isNotEmpty(splInfoDTO.getRgnCyCd())) {
				rgnCdList.add(splInfoDTO.getRgnCyCd());
			}
		}
		//查询地区
		Map<String, SysRegionDTO> regionCdMap = this.sysRegionApiService.
				searchRegionByRgnCd(rgnCdList, PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));

		for (SplVisitRecVO splVisitRecVO : list) {
			// 职位信息
			String currentOrgCd = splVisitRecVO.getCurOrgCd();
			if (StringUtils.isNotEmpty(currentOrgCd)) {
				if (currentOrgCd.length() == 12) {
					splVisitRecVO.setCrtUsrPosition("省总");
				} else if (currentOrgCd.length() == 16) {
					splVisitRecVO.setCrtUsrPosition("客户经理");
					List<SysUsrDatAuthRDTO> list1 = this.priorityApiService.searchSysUsrDatAuthRWithOrgCdList(
							splVisitRecVO.getCrtUsrId(), null, CurrentThreadContext.getFlServiceSysCd());
					for (SysUsrDatAuthRDTO sysUsrDatAuthRDTO : list1) {
						if (sysUsrDatAuthRDTO.getIsChg() == 1) {
							splVisitRecVO.setCrtUsrPosition("分公司经理");
							break;
						}
					}
				}
			}
						
			for (Map.Entry<String, String> entry : purpCdMap.entrySet()) {// 遍历拜访目的
				if (entry.getKey().equals(splVisitRecVO.getVisitPurpCd())
						|| entry.getValue().equals(splVisitRecVO.getVisitPurpCd())) {
					splVisitRecVO.setVisitPurpCd(entry.getValue());
					break;
				}
			}
			for (Map.Entry<String, String> entry : conTypCdMap.entrySet()) {// 遍历联系人类型
				if (entry.getKey().equals(splVisitRecVO.getConTypCd())
						|| entry.getValue().equals(splVisitRecVO.getConTypCd())) {
					splVisitRecVO.setConTypCd(entry.getValue());
					break;
				}
			}
			if(StringUtils.isNotEmpty(splVisitRecVO.getOffsetDistance())){
				splVisitRecVO.setSignInDis(splVisitRecVO.getOffsetDistance().longValue());
			}else{
				for (SplPositionInfoVO splPositionInfoVO : positionList) {// 遍历地理位置,查询签到距离
					if (splVisitRecVO.getPositId().equals(splPositionInfoVO.getId())) {
						// 不调用高德地图工具类 已地球半径R=6370996.81m 求球表面上两点的距离
						// 地球半径 单位 m
						double R = 6370996.81;
						double lat1 = (Math.PI / 180) * Double.valueOf(splPositionInfoVO.getPositLatitude());
						double lat2 = (Math.PI / 180) * Double.valueOf(splVisitRecVO.getPositLatitude());
						double lon1 = (Math.PI / 180) * Double.valueOf(splPositionInfoVO.getPositLongitude());
						double lon2 = (Math.PI / 180) * Double.valueOf(splVisitRecVO.getPositLongitude());
						// 两点间距离 m，如果想要千米的话，结果/1000就可以了
						double d = Math.sin(lat1) * Math.sin(lat2)
								+ Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
						if (d > 1) {
							d = 1;
						}
						if (d < -1) {
							d = -1;
						}
						double dis = Math.acos(d) * R;
						DecimalFormat df = new DecimalFormat("#");
						String format = df.format(dis);
						splVisitRecVO.setSignInDis(Long.valueOf(format));
						break;
					}
				}
			}

			for (SysOrgDTO sysOrgDTO : sysOrgList) {
				if (StringUtils.isNotEmpty(splVisitRecVO.getBuOrgCd())) {
					if (splVisitRecVO.getBuOrgCd().equals(sysOrgDTO.getOrgCd())
							|| splVisitRecVO.getBuOrgCd().equals(sysOrgDTO.getOrgDispNm())) {
						splVisitRecVO.setBuOrgCdNm(sysOrgDTO.getOrgDispNm());
					}
				}
				if (StringUtils.isNotEmpty(splVisitRecVO.getCurOrgCd())) {
					if (splVisitRecVO.getCurOrgCd().length() == 16) {
						if (splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgCd())
								|| splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgDispNm())) {
							splVisitRecVO.setCurOrgCdNm(sysOrgDTO.getOrgNm());
						}
						splVisitRecVO.setCurPrOrgCd(splVisitRecVO.getCurOrgCd().substring(0, 12));
						if (splVisitRecVO.getCurPrOrgCd().equals(sysOrgDTO.getOrgCd())) {
							splVisitRecVO.setCurPrOrgCdNm(sysOrgDTO.getOrgNm());
						}
					} else if (splVisitRecVO.getCurOrgCd().length() == 12 && !splVisitRecVO.getCurOrgCd().equals("000000010024")) {
						splVisitRecVO.setCurPrOrgCd(splVisitRecVO.getCurOrgCd());
						if (splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgCd())
								|| splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgDispNm())) {
							splVisitRecVO.setCurPrOrgCdNm(sysOrgDTO.getOrgNm());
						}
					} else if (splVisitRecVO.getCurOrgCd().length() == 20) {
						if (splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgCd())
								|| splVisitRecVO.getCurOrgCd().equals(sysOrgDTO.getOrgDispNm())) {
							splVisitRecVO.setCurOrgCdNm(sysOrgDTO.getOrgNm());
						}
						splVisitRecVO.setCurPrOrgCd(splVisitRecVO.getCurOrgCd().substring(0, 16));
						if (splVisitRecVO.getCurPrOrgCd().equals(sysOrgDTO.getOrgCd())) {
							splVisitRecVO.setCurPrOrgCdNm(sysOrgDTO.getOrgNm());
						}
						splVisitRecVO.setBuOrgCd(splVisitRecVO.getCurOrgCd().substring(0, 12));
						if (splVisitRecVO.getBuOrgCd().equals(sysOrgDTO.getOrgCd())
								|| splVisitRecVO.getBuOrgCd().equals(sysOrgDTO.getOrgDispNm())) {
							splVisitRecVO.setBuOrgCd(sysOrgDTO.getOrgDispNm());
						}
					}
				}
			}

			StringBuilder rgnNm = new StringBuilder();
			for (SplInfoDTO splInfoDTO : splInfoList) { // 遍历供应商对象,封装供应商地区
				if (splInfoDTO.getId().equals(splVisitRecVO.getSplId())) {
					if (StringUtils.isNotEmpty(splInfoDTO.getRgnPrCd())) {
						splVisitRecVO.setRgnPrCd(splInfoDTO.getRgnPrCd());
					}
					if (StringUtils.isNotEmpty(splInfoDTO.getRgnCyCd())) {
						splVisitRecVO.setRgnPrCd(splInfoDTO.getRgnCyCd());
					}
					if (StringUtils.isNotEmpty(splInfoDTO.getRgnPrCd())) {
						if (StringUtils.isNotEmpty(splInfoDTO.getRgnCyCd())) {
							if (null != regionCdMap.get(splInfoDTO.getRgnPrCd())) {
								rgnNm.append(regionCdMap.get(splInfoDTO.getRgnPrCd()).getRgnNm());
								rgnNm.append("-");
								rgnNm.append(regionCdMap.get(splInfoDTO.getRgnCyCd()).getRgnNm());
								splVisitRecVO.setSplRgnNm(rgnNm.toString());
								rgnNm.setLength(0);
							}
						} else {
							if (null != regionCdMap.get(splInfoDTO.getRgnPrCd())) {
								rgnNm.append(regionCdMap.get(splInfoDTO.getRgnPrCd()).getRgnNm());
								splVisitRecVO.setSplRgnNm(rgnNm.toString());
								rgnNm.setLength(0);
							}
						}
					}
				}
			}
			for (SplRlPsnDTO rlPsnDTO : rlPsnList) {
				if (null != rlPsnDTO) {
					if (StringUtils.isNotEmpty(rlPsnDTO.getSplId())) {
						if (rlPsnDTO.getSplId().equals(splVisitRecVO.getSplId())) {
							if (rlPsnDTO.getId().equals(splVisitRecVO.getConUsrId())) {
								splVisitRecVO.setIsRelDecision(rlPsnDTO.getIsRelDecision());
							}
						}
					}
				}
			}
		}
		return list;
	}

	@Override
	public List<SplVisitRecVO> searchSplVisitRecList(SplVisitRecQC condition2) throws BaseException {
		// TODO Auto-generated method stub
		if (null == condition2) {
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "查询条件不能为空!");
		}
		return SplVisitRecVOTransform.toVOList(this.splVisitRecApiService.searchSplVisitRecList(condition2));
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchAnalysisListPage(Pager page) throws BaseException {
		Pager pager = this.splVisitRecApiService.searchAnalysisListPage(page);
		if (null == pager) {
			return null;
		}
		List<SplVisitRecDataAnalysisDTO> dtoList = (List<SplVisitRecDataAnalysisDTO>) pager.getResultList(); 
		//System.out.println("=-=" + JSONObject.toJSONString(dtoList));
		if (CollectionUtils.isEmpty(dtoList)) {
			return null;
		}
		List<SplVisitRecDataAnalysisVO> voList = SplVisitRecDataAnalysisVOTransform.toVOList(dtoList);
		pager.setResultList(voList);
		return pager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchSplAnalysisForVisitListPage(Pager pager) throws BaseException {
		if (null == pager) {
			return null;
		} else {
			Object condition = pager.getCondition();
			if (null == condition) {
				return null;
			}
		}
		Pager resultPage = this.splVisitRecApiService.searchSplAnalysisForVisitListPage(pager);
		if (null == resultPage) {
			return null;
		}
		List<SplVisitRecDataAnalysisDTO> dtoList = (List<SplVisitRecDataAnalysisDTO>) resultPage.getResultList();
		if (CollectionUtils.isEmpty(dtoList)) {
			return null;
		}
		List<SplVisitRecDataAnalysisVO> voList = SplVisitRecDataAnalysisVOTransform.toVOList(dtoList);
		
		SplVisitRecQC condition = (SplVisitRecQC) pager.getCondition();
		// 筛选条件
		List<SplVisitRecDTO> visitList = this.splVisitRecApiService.searchSplVisitRecList(condition);
		Map<Long, SplVisitRecDTO> visitMap = new HashMap<Long, SplVisitRecDTO>();
		for (SplVisitRecDTO splVisitRecDTO : visitList) {
			visitMap.put(splVisitRecDTO.getSplId(), splVisitRecDTO);
		}
		
		SysOrgQueryCondition orgCondition = new SysOrgQueryCondition();
		orgCondition.setOrgCd(visitList.get(0).getBuOrgCd());
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchSysOrgList(orgCondition);// 查询组织架构名称
		Map<String, String> orgMap = new HashMap<String, String>();
		for (SysOrgDTO sysOrgDTO : orgList) {
			orgMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO.getOrgDispNm());
		}
		
		for (SplVisitRecDataAnalysisVO vo : voList) {
			Long splId = vo.getSplId();
			SplVisitRecDTO visitDTO = visitMap.get(splId);
			vo.setSplNm(visitDTO.getSplNm());
			vo.setSplAddr(visitDTO.getVisitPositAddr());
			vo.setCstManagerNm(visitDTO.getCrtUsrNm());
			vo.setOrgCdNm(orgMap.get(visitDTO.getBuOrgCd()));
		}
		
		resultPage.setResultList(voList);
		
		return resultPage;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String exportVisitAnalysis(Pager page) throws BaseException {
		Pager searchPage = this.splVisitRecApiService.searchAnalysisListPage(page);
		List<SplVisitRecDataAnalysisDTO> visitList = (List<SplVisitRecDataAnalysisDTO>) searchPage.getResultList();
		List<SplVisitRecDataAnalysisVO> list = SplVisitRecDataAnalysisVOTransform.toVOList(visitList);
		//list = this.dataPackage(list);
		
		ExportParams params = new ExportParams(null, null, ExcelType.XSSF);
		params.setTitleHeight((short) 5);
		params.setColor(HSSFColor.GREY_25_PERCENT.index);// 表头颜色
		params.setHeaderColor(HSSFColor.WHITE.index);
		Workbook workbook = (Workbook) ExcelExportUtil.exportExcel(params, SplVisitRecDataAnalysisVO.class, list);
		String filePath = "visitrec";
		String serverFilePath = this.getServerFilePath(filePath);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		serverFilePath = serverFilePath + "效能统计" + sdf.format(new Date()) + ".xlsx";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(serverFilePath);
			workbook.write(fos);
			fos.flush();
		} catch (FileNotFoundException e) {
			BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, e.getMessage());
		} catch (Exception e) {
			BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700,
					BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
		} finally {
			try {
				if (null != fos) {
					fos.close();
				}
			} catch (IOException e) {
				BaseLogUtils.newWebLogger("导出拜访记录失败,系统异常").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.setThrowable(e)
						.error(LogExceptionEnum.COMMON_CODE_0099);
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700,
						BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
			}
		}
		String serverPath = serverFilePath.replace(
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		return serverPath;
	}

	@Override
	public Pager selectSplBisicVisitListPage(Pager page) throws BaseException {
		if (null == page) {
			page = new Pager();
		}
		Pager pager = this.splVisitRecApiService.selectSplBisicVisitRecListPage(page);
		List<SplVisitRecDTO> resultList = (List<SplVisitRecDTO>) pager.getResultList();
		if (CollectionUtils.isNotEmpty(resultList)) {
			List<SplVisitRecVO> list = this.dataPackage(SplVisitRecVOTransform.toVOList(resultList));
			pager.setResultList(list);
		}
		return pager;
	}
}